import React, { useEffect, useRef } from 'react';
import { Row, Col, Button, message } from 'antd';

import { connect } from 'react-redux';
import CustomForm from 'src/components/CustomForm';
import services from 'src/services/api';
import ColorPicker from 'src/components/ColorPicker';
import { Skin } from 'src/utils/skinVars';
import PreviewUploadComponent from 'src/components/Upload/previewImg';
import Modal from 'src/components/Modal';
import './index.less';

function SkinSetting(props) {
  const form = useRef(null);
  const skin = useRef(null);
  const skin_color = useRef(props.skin.skin_color);
  const font_color = useRef(props.skin.font_color);
  const primary_color = useRef(props.skin.primary_color);
  useEffect(() => {
    skin.current = new Skin({
      skinColor: skin_color,
      fontColor: font_color,
      prColor: primary_color,
    });
  }, []);

  useEffect(() => {
    skin_color.current = props.skin.skin_color;
    form.current.setFieldsValue({ skin_color: { color: props.skin.skin_color } });
  }, [props.skin.skin_color]);
  useEffect(() => {
    font_color.current = props.skin.font_color;
    form.current.setFieldsValue({ font_color: { color: props.skin.font_color } });
  }, [props.skin.font_color]);
  useEffect(() => {
    primary_color.current = props.skin.primary_color;
    form.current.setFieldsValue({ primary_color: { color: props.skin.primary_color } });
  }, [props.skin.primary_color]);

  function handleSubmit() {
    form.current.validateFields((err, values) => {
      if (!err) {
        try {
          const params = {
            font_color: values.font_color.color,
            primary_color: values.primary_color.color,
            skin_color: values.skin_color.color,
            s_logo: values.s_logo.fileUrl,
            b_logo: values.b_logo.fileUrl,
          };
          services.skin.saveInfo({ theme: JSON.stringify(params) }).then((res) => {
            if (res.code === 0) {
              message.success(res.msg);
              props.dispatch({ type: 'skin/querySkinInfo', params: {} });
            } else {
              message.error(res.msg);
            }
          });
        } catch (err) {
          message.warning(err);
          return;
        }
      }
    });
  }

  function resetSkin() {
    Modal.open({
      title: '',
      width: '360px',
      isConfirm: true,
      content: <p>确定要恢复到默认主题么?</p>,
      isOkBtn: true,
      isCancelBtn: true,
      ok: () => {
        services.skin.saveInfo({ theme: '' }).then((res) => {
          if (res.code === 0) {
            message.success(res.msg);
            props.dispatch({ type: 'skin/querySkinInfo', params: {} }).then(() => {
              form.current.setFieldsValue({
                s_logo: { fileUrl: '' },
                b_logo: { fileUrl: '' },
              });
            });
            Modal.close();
          } else {
            message.error(res.msg);
          }
        });
      },
      cancel: () => {
        Modal.close();
      },
    });
  }

  function handleChangeSkin(color) {
    props.dispatch({ type: 'skin/updatePreview', data: { skin_color: color } });
    skin_color.current = color;
    changeNow();
  }
  function changeNow() {
    skin.current.getSkin(skin_color.current);
    skin.current.getFont(font_color.current);
    skin.current.getPrimary(primary_color.current);
    skin.current.changeLess();
  }

  function handleChangeFont(color) {
    props.dispatch({ type: 'skin/updatePreview', data: { font_color: color } });
    font_color.current = color;
    changeNow();
  }

  function handleChangePrimary(color) {
    props.dispatch({ type: 'skin/updatePreview', data: { primary_color: color } });
    primary_color.current = color;
    changeNow();
  }

  const b_config = {
    isCropper: true,
    aspectRatio: 150 / 40,
    r_w: 150,
    r_h: 40,
  };
  const s_config = {
    isCropper: true,
    aspectRatio: 60 / 50,
    r_w: 30,
    r_h: 25,
  };
  const formItems = [
    {
      label: {
        label: 'LOGO上传(大)',
        className: 'tantuer-form-item tantuer-form-item-nowrap',
        help: <>左上角顶部,侧边栏展开时使用以及登录页使用(大小限制5M,格式支持PNG/JPG/JPEG/SVG)</>,
      },
      name: 'b_logo',
      options: {
        initialValue: { fileUrl: props.skin.b_logo },
      },
      component: <PreviewUploadComponent {...b_config} />,
    },
    {
      label: {
        label: 'LOGO上传(小)',
        className: 'tantuer-form-item tantuer-form-item-nowrap',
        help: <>左上角顶部，侧边栏收起来时使用(大小限制5M,格式支持PNG/JPG/JPEG/SVG)</>,
      },
      name: 's_logo',
      options: {
        initialValue: { fileUrl: props.skin.s_logo },
      },
      component: <PreviewUploadComponent {...s_config} />,
    },
    {
      label: {
        label: '主题颜色',
        className: 'tantuer-form-item tantuer-form-item-nowrap',
        help: <>侧边栏和顶部的背景颜色，影响整体风格</>,
      },
      name: 'skin_color',
      options: {
        initialValue: { color: props.skin.skin_color },
      },
      component: <ColorPicker onChange={(color) => handleChangeSkin(color.color)} />,
    },
    {
      label: {
        label: '按钮颜色',
        className: 'tantuer-form-item tantuer-form-item-nowrap',
        help: <>按钮颜色、高亮颜色、链接颜色等</>,
      },
      name: 'primary_color',
      options: {
        initialValue: { color: props.skin.primary_color },
      },
      component: <ColorPicker onChange={(color) => handleChangePrimary(color.color)} />,
    },
    {
      label: {
        label: '顶部/侧边栏字颜色',
        className: 'tantuer-form-item tantuer-form-item-nowrap',
      },
      name: 'font_color',
      options: {
        initialValue: { color: props.skin.font_color },
      },
      component: <ColorPicker onChange={(color) => handleChangeFont(color.color)} />,
    },
  ].filter(Boolean);
  return (
    <div className='skin-setting'>
      <Row type='flex' justify='space-between' align='middle'>
        <Col>
          <h4>选择颜色后，立即进行预览，但是需要保存后才会永久生效</h4>
        </Col>
        <Col>
          <Button onClick={() => resetSkin()}>恢复默认主题</Button>
        </Col>
      </Row>

      <CustomForm
        colNum={1}
        className='skin-setting-form'
        createForm={(ref) => (form.current = ref)}
        formItems={formItems}
        onHandleSubmit={() => handleSubmit()}
        confirmText='保存'
        help=''
      />
    </div>
  );
}

function mapStateToProps(state) {
  return {
    skin: {
      skin_color: state.skin.skin_color,
      font_color: state.skin.font_color,
      primary_color: state.skin.primary_color,
      s_logo: state.skin.s_logo,
      b_logo: state.skin.b_logo,
    },
  };
}
export default connect(mapStateToProps)(SkinSetting);
